<script setup lang="ts">
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import type { IToolbarConfig, IEditorConfig, IDomEditor } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css";
import { shallowRef, onBeforeUnmount, reactive, watch } from "vue";

defineOptions({ name: "WebxWEditor" });
/**
 * update:html：双向绑定输入内容
 * */
const emits = defineEmits(["update:html"]);
const props = defineProps({
  // 传入的html内容
  html: { type: String, default: "" }
});

// editor元素
const editorRef = shallowRef();
// tabbar的配置项
const toolbarConfig: Partial<IToolbarConfig> = {};
// editor的配置项
const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请输入内容..."
};
// 富文本属性
const weditorData = reactive({
  html: ""
});
// 富文本配置
const weditorConfig = reactive({
  mode: "default",
  onCreate(editor: IDomEditor) {
    editorRef.value = editor;
  },
  onChange(editor: IDomEditor) {
    emits("update:html", editor.getHtml());
  }
});

watch(
  () => props.html,
  () => {
    editorRef.value?.setHtml(props.html);
  }
);

// 组件卸载销毁富文本
onBeforeUnmount(() => {
  if (!editorRef.value) return;
  editorRef.value.destroy();
});
</script>

<template>
  <div class="border flex flex-col h-full">
    <Toolbar
      class="border-b flex-shrink-0"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="weditorConfig.mode"
    />
    <Editor
      class="flex-1 overflow-y-auto"
      v-model="weditorData.html"
      :defaultConfig="editorConfig"
      :mode="weditorConfig.mode"
      @onCreated="weditorConfig.onCreate"
      @onChange="weditorConfig.onChange"
    />
  </div>
</template>

<style scoped lang="less"></style>
